<script setup>
import { ref, reactive, computed, toRaw, onMounted } from "vue";
import {
  getCode,
  userAuthentication,
  login,
  menuPermissions,
} from "../../api/index";
import { useRouter } from "vue-router";
const router = useRouter();
const imgUrl = new URL("../../../public/login-head.png", import.meta.url).href;
import { UseUserStore, UseMenuStore } from "../../store/index";
const UseUserStores = UseUserStore();
const UseMenuStores = UseMenuStore();
// 新路由数据
const routerList = computed(() => UseMenuStores.routerList);
// 注册和登录控制状态
const formType = ref(0);
// 点击切换注册和登录
const handleChange = () => {
  formType.value = formType.value ? 0 : 1;
};

// 表单数据
const loginForm = ref({
  userName: "18218865354",
  passWord: "18218865354",
  validCode: "",
});

// 倒计时组件
const countdown = reactive({
  valiText: "获取验证码",
  time: 60,
});
// 点击开始倒计时
let flag = false;
const countdownChange = async () => {
  // 第一步判断是否重复发送了验证码
  if (flag) return;
  // console.log(11);

  // 第二步先校验电话号码是否正确
  const phoneReg =
    /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/;
  // console.log(loginForm.userName);

  if (!loginForm.value.userName || !phoneReg.test(loginForm.value.userName)) {
    return ElMessage({
      message: "请输入正确的手机号码",
      type: "warning",
    });
  }

  // 倒计时
  const timer = setInterval(() => {
    if (countdown.time <= 0) {
      countdown.time = 8;
      countdown.valiText = "获取验证码";
      flag = false;
      clearInterval(timer);
    } else {
      countdown.time -= 1;
      countdown.valiText = `${countdown.time}s后重新获取`;
    }
  }, 1000);

  flag = true;

  // 发送请求获取验证码
  const res = await getCode({
    tel: loginForm.value.userName,
  });
  // console.log(res.data.code);

  if (res.data.code === 10000) {
    ElMessage.success("发送成功");
  }
};

// 表单校验，校验prop的数据
const validateUser = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请输入手机号"));
  } else {
    const phoneReg =
      /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/;
    phoneReg.test(value)
      ? callback()
      : callback(new Error("请输入正确的手机号"));
  }
};
const validatePass = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请输入密码"));
  } else {
    const reg = /^[a-zA-Z0-9_-]{4,16}$/;
    reg.test(value)
      ? callback()
      : callback(new Error("请输入4-16位正确的密码"));
  }
};
const rules = reactive({
  userName: [{ validator: validateUser, trigger: "blur" }],
  passWord: [{ validator: validatePass, trigger: "blur" }],
});

const loginFormRef = ref();
// 点击注册登录
const submitForm = async (formEl) => {
  // 先判断有没有拿到表单示例
  if (!formEl) return;
  // 再触发校验
  await formEl.validate((valid, fields) => {
    if (valid) {
      // 成功执行
      // 判断是注册还是登录
      if (formType.value) {
        // 注册
        userAuthentication(loginForm.value).then(({ data }) => {
          if (data.code === 10000) {
            // console.log(data);

            ElMessage.success("注册成功,请登录");
          }
        });
      } else {
        // 登录
        login(loginForm.value).then(({ data }) => {
          if (data.code === 10000) {
            ElMessage.success("登录成功");
            // 登录成功，把信息缓存到本地
            UseUserStores.pz_token = data.data.token;
            UseUserStores.pz_userInfo = data.data.userInfo;
            // 获取菜单权限
            menuPermissions().then(({ data }) => {
              UseMenuStores.dynamicMenu(data.data);
              // console.log(data);
              // routerList.value = UseMenuStores.routerList;
              toRaw(routerList.value).forEach((item) => {
                router.addRoute("main", item);
              });
              // console.log(routerList);
              UseMenuStores.routerList = routerList.value;
              // 跳转主页面
              router.push("/");
            });
          }
        });
      }
      // console.log(loginForm, "submit");
    } else {
      // 错误执行
      console.log(fields, "error submit");
    }
  });
  // 校验成功调用接口
};
</script>

<template>
  <el-row class="login-container" justify="center" :align="'middle'">
    <el-card style="max-width: 480px">
      <template #header>
        <div class="card-header">
          <img :src="imgUrl" alt="" />
        </div>
      </template>
      <div class="jump-link">
        <el-link type="primary" @click="handleChange">
          {{ formType ? "返回登录" : "注册账号" }}
        </el-link>
      </div>
      <!-- 表单 -->
      <el-form
        :model="loginForm"
        ref="loginFormRef"
        :rules="rules"
        style="max-width: 600px"
        class="demo-ruleForm"
      >
        <!-- 手机号 -->
        <el-form-item prop="userName">
          <el-input v-model="loginForm.userName" placeholder="手机号">
            <template #prefix>
              <el-icon><UserFilled /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item prop="passWord">
          <el-input
            v-model="loginForm.passWord"
            placeholder="密码"
            type="password"
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <!-- 验证码 -->
        <el-form-item prop="validCode" v-if="formType">
          <el-input v-model="loginForm.validCode" placeholder="验证码">
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
            <template #append>
              <span @click="countdownChange">{{ countdown.valiText }}</span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            style="width: 100%"
            @click="submitForm(loginFormRef)"
          >
            {{ formType ? "手机号注册" : "账号登录" }}</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
  </el-row>
</template>

<style scoped lang="less">
:deep(.el-card__header) {
  padding: 0;
}
.login-container {
  height: 100%;
  .card-header {
    background-color: #899fe1;
    img {
      width: 430px;
    }
  }
  .jump-link {
    text-align: right;
    margin-bottom: 10px;
  }
}
</style>
